import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/** 
 * 
 * @author Administrator 
 */
public class JPassWordDialog extends JDialog implements ActionListener, WindowListener {
	private String userName, userPassword;

	private JLabel name, password;

	private JTextField nameField;

	private JPasswordField passwordField;

	public JPassWordDialog() {
		this.setTitle("登陆对话框");

		this.name = new JLabel("用户名：");
		this.password = new JLabel("口令: ");

		Box horBox = Box.createHorizontalBox();
		horBox.add(Box.createHorizontalStrut(50));

		Box box = Box.createVerticalBox();
		box.add(Box.createVerticalStrut(40));
		box.add(this.name);
		box.add(Box.createVerticalStrut(20));
		box.add(this.password);
		box.add(Box.createVerticalStrut(100));
		horBox.add(box);

		horBox.add(Box.createHorizontalStrut(20));

		this.nameField = new JTextField(5);
		this.nameField.addActionListener(this);
		this.passwordField = new JPasswordField(5);
		this.passwordField.addActionListener(this);

		box = Box.createVerticalBox();
		box.add(Box.createVerticalStrut(40));
		box.add(this.nameField);
		box.add(Box.createVerticalStrut(20));
		box.add(this.passwordField);
		box.add(Box.createVerticalStrut(100));
		horBox.add(box);

		horBox.add(Box.createHorizontalStrut(90));

		Container contentPane = this.getContentPane();
		contentPane.add(horBox);

		this.setSize(350, 200);
		this.setVisible(true);
		this.validate();
		this.addWindowListener(this);
	}

	public void setCode(String name, String password) {
		this.userName = name;
		this.userPassword = password;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == this.nameField) {
			this.passwordField.requestFocus();
		} else if (e.getSource() == this.passwordField) {
			if (this.userName.equals(this.nameField.getText()) && this.userPassword.equals((String.copyValueOf(this.passwordField.getPassword())))) {
				JOptionPane.showMessageDialog(this, "恭喜了！", "登陆消息框", JOptionPane.INFORMATION_MESSAGE);
				this.dispose();
			} else {
				JOptionPane.showMessageDialog(this, "密码或用户名不对！请重新输入!", "登陆消息框", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	public void windowOpened(WindowEvent e) {

	}

	public void windowClosing(WindowEvent e) {
		int result = JOptionPane.showConfirmDialog(this, "是否退出本系统！", "退出消息框", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		if (result == JOptionPane.YES_OPTION) {
			System.exit(0);
		} else if (result == JOptionPane.NO_OPTION) {
			this.setVisible(true);
			this.validate();
		}
	}

	public void windowClosed(WindowEvent e) {

	}

	public void windowIconified(WindowEvent e) {

	}

	public void windowDeiconified(WindowEvent e) {

	}

	public void windowActivated(WindowEvent e) {

	}

	public void windowDeactivated(WindowEvent e) {

	}
	
	public static void main(String[] args) {
		new JPassWordDialog();
	}
}